﻿using LPP.Entity.Addresses;
using LPP.Service.AddressService;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace LPP.API.Controllers.AddressController
{
    [ApiController]
    [Route("api/[controller]")]
    public class AddressController : ControllerBase
    {
        private readonly IAddressService _addressService;
        private readonly ILogger<AddressController> _logger;

        public AddressController(IAddressService addressService, ILogger<AddressController> logger)
        {
            _addressService = addressService;
            _logger = logger;
        }

        /// <summary>
        /// 获取用户的地址列表
        /// </summary>
        [HttpGet("{userId}")]
        public async Task<IActionResult> GetAddresses(int userId)
        {
            try
            {
                _logger.LogInformation($"正在获取用户ID {userId} 的地址信息");

                var addresses = await _addressService.GetAddressAsync(userId);

                // 如果没有找到地址，返回空数组而不是404
                if (addresses == null || !addresses.Any())
                {
                    _logger.LogInformation($"用户 {userId} 没有保存的地址");
                    return Ok(new List<Address>());
                }

                // 转换为前端需要的格式
                var formattedAddresses = addresses.Select(a => new
                {
                    a.AddressID,
                    a.UserID,
                    a.ContactName,
                    a.PhoneNumber,
                    a.City,
                    a.AddressDetail,
                    a.BuildingNumber,
                    // 组合完整地址
                    FullAddress = $"{a.City} {a.AddressDetail} {a.BuildingNumber}"
                }).ToList();

                return Ok(formattedAddresses);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取用户 {userId} 的地址时发生错误");
                return StatusCode(500, new
                {
                    Message = "获取地址信息失败",
                    Error = ex.Message
                });
            }
        }

        /// <summary>
        /// 添加新地址
        /// </summary>
        [HttpPost("add")]
        public async Task<IActionResult> AddAddress([FromBody] Address address)
        {
            try
            {
                _logger.LogInformation($"正在为用户 {address.UserID} 添加新地址");

                if (!ModelState.IsValid)
                {
                    var errors = ModelState.Values
                        .SelectMany(v => v.Errors)
                        .Select(e => e.ErrorMessage)
                        .ToList();
                    return BadRequest(new { Message = "数据验证失败", Errors = errors });
                }

                // 验证必要字段
                if (string.IsNullOrEmpty(address.City) ||
                    string.IsNullOrEmpty(address.AddressDetail) ||
                    string.IsNullOrEmpty(address.ContactName) ||
                    string.IsNullOrEmpty(address.PhoneNumber))
                {
                    return BadRequest(new { Message = "请填写完整的地址信息" });
                }

                var result = await _addressService.AddAddressAsync(address);
                if (!result)
                {
                    return BadRequest(new { Message = "添加地址失败" });
                }

                return Ok(new
                {
                    Message = "地址添加成功",
                    Address = new
                    {
                        address.AddressID,
                        address.UserID,
                        address.ContactName,
                        address.PhoneNumber,
                        address.City,
                        address.AddressDetail,
                        address.BuildingNumber,
                        FullAddress = $"{address.City} {address.AddressDetail} {address.BuildingNumber}"
                    }
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"添加地址时发生错误: {ex.Message}");
                return StatusCode(500, new
                {
                    Message = "添加地址失败",
                    Error = ex.Message
                });
            }
        }

        /// <summary>
        /// 删除地址
        /// </summary>
        [HttpDelete("{addressId}")]
        public async Task<IActionResult> DeleteAddress(int addressId)
        {
            try
            {
                var result = await _addressService.DeleteAddressAsync(addressId);
                if (!result)
                {
                    return BadRequest(new { Message = "删除地址失败" });
                }

                return Ok(new { Message = "地址删除成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"删除地址时发生错误: {ex.Message}");
                return StatusCode(500, new
                {
                    Message = "删除地址失败",
                    Error = ex.Message
                });
            }
        }

        /// <summary>
        /// 更新地址
        /// </summary>
        [HttpPut("{addressId}")]
        public async Task<IActionResult> UpdateAddress(int addressId, [FromBody] Address address)
        {
            try
            {
                if (addressId != address.AddressID)
                {
                    return BadRequest(new { Message = "地址ID不匹配" });
                }

                var result = await _addressService.UpdateAddressAsync(address);
                if (!result)
                {
                    return BadRequest(new { Message = "更新地址失败" });
                }

                return Ok(new { Message = "地址更新成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新地址时发生错误: {ex.Message}");
                return StatusCode(500, new
                {
                    Message = "更新地址失败",
                    Error = ex.Message
                });
            }
        }
    }
}





